#!/bin/bash

. $OPENARS_HOME/common/debug.h
. $OPENARS_HOME/common/functions.h

user=$USER_ARS
[ -z "$user" ] && user=$LOGNAME

:>$OUTFILE

# $OUTFILE --> CMDB
function update_db() {
if [ -z "$CONNECT_ARS" ]; then
    ERR "not defined CONNECT_ARS environment for Oracle connect. exit."
    exit 1;
fi

$ORACLE_HOME/bin/sqlplus -s /NOLOG << END
    set serveroutput on
    set feedback off
    connect $CONNECT_ARS
    spool $TEMPDIR/megre_all_users_info.out
    @"$OUTFILE"
    commit;
    spool off
    exit;
END
    return 0
}

srvlist=`get_hosts --os=Unix --control=YES`
INF "`echo $srvlist | wc -w | awk '{print $1}'` hosts"

SUDO=/usr/local/bin/sudo
[ -z $USER ] && USER=$LOGNAME
command="cat /etc/passwd > ./passwd1; \
	 cat /etc/group > ./group1; \
	 $SUDO cat /etc/shadow > ./shadow1; \
	 $SUDO cat /usr/local/etc/sudoers > ./sudoers1"


for server in $srvlist ; do

	( result=""
	  SSH $USER_ARS@$server "$command"
	  [ $? -eq 255 ] && continue
	    >$TEMPDIR/$server.OK
	    sftp $USER_ARS@$server 2>/dev/null << END
		get ./passwd1  $TEMPDIR/$server.passwd
		get ./group1   $TEMPDIR/$server.group
		get ./shadow1  $TEMPDIR/$server.shadow
		get ./sudoers1 $TEMPDIR/$server.sudoers
		rm ./passwd1
		rm ./group1
		rm ./shadow1
		rm ./sudoers1
END
	) &
done

wait

cd $TEMPDIR
INF "create sql-commands ..."

    srvlist=`ls *.OK | awk -F. '{print $1}'`
    for server in $srvlist
    do
	flag=""
	for file in passwd group shadow sudoers
	do
	    flag="ok"
	    if [ ! -s $server.$file ]; then
		ERR "not get $file from $server"
		flag=""	
	    fi
	done
	[ -z "$flag" ] && continue
	while read line
	do
	    host=" "; user_name=" "; user_id=" "; group_id=" "; etc_passwd=" "; etc_group=" "; etc_shadow=" "; sudo=" "; errors=" ";
	    host=$server
	    user_name=`echo $line | awk -F: '{print $1}'`
	    user_id=`echo $line | awk -F: '{print $3}'`
	    type_user=" "
	    group_id=`echo $line | awk -F: '{print $4}'`
	    etc_passwd=$line
	    #etc_group=`cat $server.group | awk -F: '$3=='$group_id'{print}' | sed -n 1p | sed -e 's/^\(.\{145\}\).*$/\1\ \.\.\./'` 
	    groups=`cat $server.group | sed s/$/:/ | awk -F: '$3=='$group_id' || /[:,]'$user_name'[:,]/ {print $1}'`
	    etc_group=`echo $groups | sed s/\ /,/g` 
	    etc_shadow=`cat $server.shadow | grep ^$user_name: | sed -n 1p`
	    # sed: "" --> " " (not NULL)
	    echo "exec merge_all_users_info ('$host', '$user_name', '$user_id', '$etc_passwd', '$etc_group', '$etc_shadow', '$sudo', '$errors');" | sed "s/\&//g" | sed "s/\'\'/\' \'/" >> $OUTFILE
	done < $server.passwd
    done

INF "check table ALL_USERS_INFO ..."
result=`update_db`
if [ "$?" -ne 0 ]; then
    ERR "error function update_db()"
    exit 1
fi

if [ -s "$TEMPDIR/megre_all_users_info.out" ]; then
 while read line
 do
    WARN "$line"
 done < $TEMPDIR/megre_all_users_info.out
fi

exit 0
